<?php
namespace app\admin\controller;

use think\facade\View;

use app\admin\model\TopicContent as ContentModel;
use app\admin\model\TopicSun as SunModel;

/**
 * 子专题管理
 * @author huwhis@163.com
 * @version   0.0.1
 */
class TopicSun extends Base
{
    public function index($id = 0)
    {
        $topicInfo = ContentModel::field('id,cid,title,topic_url,create_time')->find($id);

        $list = SunModel::where('tid', $id)->field('id,tid,title,topic_url,sort,clicks,create_time')->select();

        return View::fetch('index', [
            'list' => $list,
            'topicInfo' => $topicInfo,
        ]);
    }

    public function info($tid = 0, $id = 0)
    {
        if (!$tid) {
            $this->error('请选择专题');
        }

        if ($id) {
            $data = SunModel::find($id);
        } else {
            $data = new SunModel();
        }

        return View::fetch('save', [
            'tid' => $tid,
            'data' => $data,
        ]);
    }

    public function save()
    {
        if ($this->app->request->isPost()) {
            $param = $this->app->request->param();
            
            if (!$param['tid']) {
                $this->error('请选择专题');
            }
            
            if ($param['title'] == '') {
                $this->error("标题不能为空");
            }

            if (((int) $param['type'] == 0 || (int) $param['type'] == 1) && $param['topic_url'] == '') {
                $this->error("子专题路径不能为空");
            }

            try {
                if ($param['id'] != 0) {
                    SunModel::update($param);
                } else {
                    $param['userid'] = $this->uid;
                    $param['username'] = $this->username;

                    unset($param['id']);
                    SunModel::create($param);
                }
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误提示:".$msg);
            }

            $this->success('操作成功', url('topic_sun/index', ['tid'=>$param['tid']]));
        }
    }

    public function tslist($tid)
    {
        if ($this->app->request->isPost()) {
            if (!$tid) {
                return ['code'=>0, 'msg'=>'tid不可为空', 'list'=>[]];    
            }

            $list = SunModel::where('tid', $tid)->field('id, tid, title')->order('id desc')->select();

            return ['code'=>1, 'list'=>$list];
        }
    }
}
